﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using Vit.SchemaExplorer;

namespace Vit.Data
{
    public class SqlBuilder
    {
        public static IEnumerable<TableColumnSchema> GetColumns(TableSchema tableSchema, IEnumerable<string> columnNames)
        {
            if (columnNames == null || columnNames.Count() <= 0)
            {
                foreach (var col in tableSchema.Columns)
                    yield return col;
            }
            else
            {
                foreach (var col in tableSchema.Columns)
                    if (columnNames.Contains(col.Name))
                        yield return col;
            }
        }

        public static string BuildSelectColumns(TableSchema tableSchema, string tableAsName, IEnumerable<string> columnNames)
        {
            var columns = GetColumns(tableSchema, columnNames);
            StringBuilder sb = new StringBuilder();
            foreach (var col in columns)
                sb.AppendFormat("{0}{1},", 
                    string.IsNullOrEmpty(tableAsName) ? "" : string.Concat(tableAsName, ","), 
                    col.SafeName);
            return sb.ToString().TrimEnd(',');
        }

        public static string BuildPrimaryCondition<TEntity>(TableSchema tableSchema, string tableAsName, TEntity entity, out List<DbParameter> parameters)
            where TEntity : EntityBase, new()
        {
            StringBuilder sb = new StringBuilder();
            
            parameters = new List<DbParameter>();
            foreach (var pk in tableSchema.PrimaryKeys)
            {
                foreach (var col in pk.KeyColumns)
                {
                    sb.AppendFormat("{0}{1}={2},",
                        string.IsNullOrEmpty(tableAsName) ? "" : string.Concat(tableAsName, ","), 
                        col.SafeName,
                        col.ParameteredName);
                    parameters.Add(new OleDbParameter()
                    {
                        Direction = ParameterDirection.Input,
                        ParameterName = col.ParameteredName,
                        DbType = col.DataType,
                        Value = entity.GetProperty(col.Name, null)
                    });
                }
            }
            return sb.ToString().TrimEnd(',').Replace(",", " AND ");
        }
    }
}
